import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_base/src/config/app_colors.dart';
import 'package:flutter_base/src/utils/navigation_service.dart';

// --- 占位符组件 ---
// FilterDateWidget 保持不变，用于其他模式
class FilterDateWidget extends StatefulWidget {
  final DateTime initialDateTime;
  final ValueChanged<DateTime> onDateTimeChanged;
  final FilterType filterType;
  final int yearsBack;

  const FilterDateWidget({
    super.key,
    required this.initialDateTime,
    required this.onDateTimeChanged,
    required this.filterType,
    required this.yearsBack,
  });

  @override
  State<FilterDateWidget> createState() => _FilterDateWidgetState();
}

class _FilterDateWidgetState extends State<FilterDateWidget> {
  late int selectedYear;
  late int selectedMonth;
  late int selectedWeek;

  late FixedExtentScrollController yearController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController weekController;

  late int minYear;
  late int maxYear;

  @override
  void initState() {
    super.initState();

    maxYear = DateTime.now().year;
    minYear = maxYear - widget.yearsBack;

    selectedYear = widget.initialDateTime.year;
    selectedMonth = widget.initialDateTime.month;
    selectedWeek = _getWeekOfYear(widget.initialDateTime);

    yearController = FixedExtentScrollController(initialItem: selectedYear - minYear);
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    weekController = FixedExtentScrollController(initialItem: selectedWeek - 1);
  }

  @override
  void dispose() {
    yearController.dispose();
    monthController.dispose();
    weekController.dispose();
    super.dispose();
  }

  /// 根据年份和周数计算出该周的第一天
  DateTime _getDateForWeek(int year, int week) {
    final firstDayOfYear = DateTime(year, 1, 1);
    final dayOfWeek = firstDayOfYear.weekday;
    final firstMonday = firstDayOfYear.subtract(Duration(days: dayOfWeek - 1));
    return firstMonday.add(Duration(days: (week - 1) * 7));
  }

  /// 计算给定日期是当年的第几周
  int _getWeekOfYear(DateTime date) {
    final firstDayOfYear = DateTime(date.year, 1, 1);
    final dayOfWeek = firstDayOfYear.weekday;
    final firstMonday = firstDayOfYear.subtract(Duration(days: dayOfWeek - 1));
    final daysDifference = date.difference(firstMonday).inDays;
    return (daysDifference / 7).ceil();
  }

  /// 计算一年有多少周
  int _getWeeksInYear(int year) {
    final lastDay = DateTime(year, 12, 31);
    return _getWeekOfYear(lastDay);
  }

  void _onSelectedItemChanged() {
    DateTime newDate;
    switch (widget.filterType) {
      case FilterType.year:
        newDate = DateTime(selectedYear);
        break;
      case FilterType.month:
        newDate = DateTime(selectedYear, selectedMonth);
        break;
      case FilterType.week:
        // 如果年变了，周数可能超出范围，需要校正
        final maxWeeks = _getWeeksInYear(selectedYear);
        if (selectedWeek > maxWeeks) {
          selectedWeek = maxWeeks;
          weekController.jumpToItem(selectedWeek - 1);
        }
        newDate = _getDateForWeek(selectedYear, selectedWeek);
        break;
    }
    widget.onDateTimeChanged(newDate);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: _buildPickerColumns(),
    );
  }

  List<Widget> _buildPickerColumns() {
    final years = List.generate(maxYear - minYear + 1, (index) => '${minYear + index}年');

    switch (widget.filterType) {
      case FilterType.year:
        return [
          _buildPickerColumn(
            context: context,
            controller: yearController,
            items: years,
            selectedIndex: selectedYear - minYear,
            width: 120,
            onChanged: (index) {
              setState(() => selectedYear = minYear + index);
              _onSelectedItemChanged();
            },
          ),
        ];
      case FilterType.month:
        final months = List.generate(12, (index) => '${(index + 1).toString().padLeft(2, '0')}月');
        return [
          _buildPickerColumn(
            context: context,
            controller: yearController,
            items: years,
            selectedIndex: selectedYear - minYear,
            width: 120,
            onChanged: (index) {
              setState(() => selectedYear = minYear + index);
              _onSelectedItemChanged();
            },
          ),
          _buildPickerColumn(
            context: context,
            controller: monthController,
            items: months,
            selectedIndex: selectedMonth - 1,
            width: 80,
            onChanged: (index) {
              setState(() => selectedMonth = index + 1);
              _onSelectedItemChanged();
            },
          ),
        ];
      case FilterType.week:
        final weeksInYear = _getWeeksInYear(selectedYear);
        final weeks = List.generate(weeksInYear, (index) => '第${index + 1}周');
        return [
          _buildPickerColumn(
            context: context,
            controller: yearController,
            items: years,
            selectedIndex: selectedYear - minYear,
            width: 120,
            onChanged: (index) {
              setState(() => selectedYear = minYear + index);
              // 年份变化，周列表需要重建，所以整个组件需要重绘
              _onSelectedItemChanged();
            },
          ),
          _buildPickerColumn(
            context: context,
            controller: weekController,
            items: weeks,
            selectedIndex: selectedWeek - 1,
            width: 120,
            onChanged: (index) {
              setState(() => selectedWeek = index + 1);
              _onSelectedItemChanged();
            },
          ),
        ];
    }
  }
}
// --- 占位符结束 ---

/// 日期选择器类型
enum DatePickerMode {
  editDate,
  filterDate,
  editTime,
  editDateTime,
}

/// 筛选类型
enum FilterType {
  week,
  month,
  year,
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++                            共享的样式代码                           +++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

/// 构建一个自定义样式的选择器列 (可被日期和时间选择器共用)
Widget _buildPickerColumn({
  required BuildContext context, // 新增 context 以获取主题
  required FixedExtentScrollController controller,
  required List<String> items,
  required int selectedIndex,
  required ValueChanged<int> onChanged,
  double? width,
}) {
  return SizedBox(
    width: width ?? 100,
    height: 250.0, // 统一高度
    child: CupertinoPicker(
      scrollController: controller,
      itemExtent: 36.0,
      onSelectedItemChanged: onChanged,
      selectionOverlay: Container(color: Colors.transparent), // 移除覆盖层
      children: List.generate(items.length, (index) {
        final bool isSelected = index == selectedIndex;
        final textStyle = TextStyle(
          fontSize: 21.0,
          color: isSelected ? AppColors.of(context).primaryColor : CupertinoColors.label.resolveFrom(context),
          fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
        );
        return Center(child: Text(items[index], style: textStyle));
      }),
    ),
  );
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++                      自定义的日期选择器 (无改动)                      +++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class _ManualDatePicker extends StatefulWidget {
  final DateTime initialDateTime;
  final ValueChanged<DateTime> onDateTimeChanged;

  const _ManualDatePicker({
    required this.initialDateTime,
    required this.onDateTimeChanged,
  });

  @override
  State<_ManualDatePicker> createState() => _ManualDatePickerState();
}

class _ManualDatePickerState extends State<_ManualDatePicker> {
  late int selectedYear;
  late int selectedMonth;
  late int selectedDay;

  late FixedExtentScrollController yearController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController dayController;

  final int minYear = 2000;
  final int maxYear = 2050;

  @override
  void initState() {
    super.initState();
    selectedYear = widget.initialDateTime.year;
    selectedMonth = widget.initialDateTime.month;
    selectedDay = widget.initialDateTime.day;

    yearController = FixedExtentScrollController(initialItem: selectedYear - minYear);
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    dayController = FixedExtentScrollController(initialItem: selectedDay - 1);
  }

  int _getDaysInMonth(int year, int month) {
    if (month == DateTime.february) {
      final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
      return isLeapYear ? 29 : 28;
    }
    const daysInMonth = <int>[31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return daysInMonth[month - 1];
  }

  void _onSelectedItemChanged() {
    final maxDays = _getDaysInMonth(selectedYear, selectedMonth);
    if (selectedDay > maxDays) {
      selectedDay = maxDays;
      dayController.jumpToItem(selectedDay - 1);
    }
    final newDate = DateTime(
      selectedYear,
      selectedMonth,
      selectedDay,
      widget.initialDateTime.hour,
      widget.initialDateTime.minute,
    );
    widget.onDateTimeChanged(newDate);
  }

  @override
  Widget build(BuildContext context) {
    final years = List.generate(maxYear - minYear + 1, (index) => '${minYear + index}年');
    final months = List.generate(12, (index) => '${(index + 1).toString().padLeft(2, '0')}月');
    final days = List.generate(_getDaysInMonth(selectedYear, selectedMonth), (index) => '${index + 1}日');

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _buildPickerColumn(
          context: context,
          controller: yearController,
          items: years,
          selectedIndex: selectedYear - minYear,
          width: 120,
          onChanged: (index) {
            setState(() {
              selectedYear = minYear + index;
            });
            _onSelectedItemChanged();
          },
        ),
        _buildPickerColumn(
          context: context,
          controller: monthController,
          items: months,
          selectedIndex: selectedMonth - 1,
          width: 80,
          onChanged: (index) {
            setState(() {
              selectedMonth = index + 1;
            });
            _onSelectedItemChanged();
          },
        ),
        _buildPickerColumn(
          context: context,
          controller: dayController,
          items: days,
          selectedIndex: selectedDay - 1,
          width: 80,
          onChanged: (index) {
            setState(() {
              selectedDay = index + 1;
            });
            _onSelectedItemChanged();
          },
        ),
      ],
    );
  }
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++                新增：我们自定义的时刻选择器                 +++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class _ManualTimePicker extends StatefulWidget {
  final DateTime initialDateTime;
  final ValueChanged<DateTime> onDateTimeChanged;

  const _ManualTimePicker({
    required this.initialDateTime,
    required this.onDateTimeChanged,
  });

  @override
  State<_ManualTimePicker> createState() => _ManualTimePickerState();
}

class _ManualTimePickerState extends State<_ManualTimePicker> {
  late int selectedHour;
  late int selectedMinute;

  late FixedExtentScrollController hourController;
  late FixedExtentScrollController minuteController;

  @override
  void initState() {
    super.initState();
    selectedHour = widget.initialDateTime.hour;
    selectedMinute = widget.initialDateTime.minute;

    hourController = FixedExtentScrollController(initialItem: selectedHour);
    minuteController = FixedExtentScrollController(initialItem: selectedMinute);
  }

  void _onSelectedItemChanged() {
    final newTime = DateTime(
      widget.initialDateTime.year,
      widget.initialDateTime.month,
      widget.initialDateTime.day,
      selectedHour,
      selectedMinute,
    );
    widget.onDateTimeChanged(newTime);
  }

  @override
  Widget build(BuildContext context) {
    // 准备 小时 和 分钟 的数据列表
    final hours = List.generate(24, (index) => index.toString().padLeft(2, '0'));
    final minutes = List.generate(60, (index) => index.toString().padLeft(2, '0'));

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 小时选择器
        _buildPickerColumn(
          context: context,
          controller: hourController,
          items: hours,
          selectedIndex: selectedHour,
          width: 80,
          onChanged: (index) {
            setState(() {
              selectedHour = index;
            });
            _onSelectedItemChanged();
          },
        ),
        // 分隔符
        const Text(":", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
        // 分钟选择器
        _buildPickerColumn(
          context: context,
          controller: minuteController,
          items: minutes,
          selectedIndex: selectedMinute,
          width: 80,
          onChanged: (index) {
            setState(() {
              selectedMinute = index;
            });
            _onSelectedItemChanged();
          },
        ),
      ],
    );
  }
}

/// 自定义日期选择器 (主类)
class CustomDatePicker {
  static void show({
    required BuildContext context,
    DateTime? initialDateTime,
    DatePickerMode mode = DatePickerMode.editDate,
    FilterType filterType = FilterType.week,
    int yearsBack = 3,
    Function(DateTime)? onChange,
    Function(DateTime)? onConfirm,
    VoidCallback? onCancel,
    String? title,
  }) {
    final DateTime initialDate = initialDateTime ?? DateTime.now();
    DateTime selectedDateTime = initialDate;
    late OverlayEntry overlayEntry;

    void handleConfirm() {
      onConfirm?.call(selectedDateTime);
      overlayEntry.remove();
    }

    void handleCancel() {
      onCancel?.call();
      overlayEntry.remove();
    }

    void handleChange(DateTime dateTime) {
      selectedDateTime = dateTime;
      onChange?.call(dateTime);
    }

    String getTitleText() {
      if (title != null) return title;
      switch (mode) {
        case DatePickerMode.editDate:
          return '编辑日期';
        case DatePickerMode.filterDate:
          return '筛选时间';
        case DatePickerMode.editTime:
          return '时刻';
        case DatePickerMode.editDateTime:
          return '编辑日期和时间';
      }
    }

    overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: handleCancel,
          child: Container(
            color: Colors.black.withValues(alpha: 0.5),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                GestureDetector(
                  onTap: () {},
                  child: Container(
                    decoration: BoxDecoration(
                      color: CupertinoColors.systemBackground.resolveFrom(context),
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(16.0),
                        topRight: Radius.circular(16.0),
                      ),
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: mode == DatePickerMode.editDateTime
                          ? _DateTimePickerBody(
                              initialDateTime: initialDate,
                              onDateTimeChanged: handleChange,
                              onCancel: handleCancel,
                              onConfirm: handleConfirm,
                              title: getTitleText(),
                            )
                          : Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Container(
                                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                                  alignment: Alignment.center,
                                  child: Text(
                                    getTitleText(),
                                    style: const TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
                                  ),
                                ),
                                _buildPickerBody(
                                  context: context,
                                  mode: mode,
                                  initialDateTime: initialDate,
                                  filterType: filterType,
                                  yearsBack: yearsBack,
                                  onDateTimeChanged: handleChange,
                                ),
                                _buildBottomButtons(handleCancel, handleConfirm),
                              ],
                            ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );

    Overlay.of(context).insert(overlayEntry);
  }

  static Widget _buildPickerBody({
    required BuildContext context,
    required DatePickerMode mode,
    required DateTime initialDateTime,
    required FilterType filterType,
    required int yearsBack,
    required ValueChanged<DateTime> onDateTimeChanged,
  }) {
    switch (mode) {
      case DatePickerMode.editDate:
        return _ManualDatePicker(initialDateTime: initialDateTime, onDateTimeChanged: onDateTimeChanged);
      case DatePickerMode.filterDate:
        return FilterDateWidget(
          initialDateTime: initialDateTime,
          filterType: filterType,
          yearsBack: yearsBack,
          onDateTimeChanged: onDateTimeChanged,
        );
      case DatePickerMode.editTime:
        // *** 使用我们新的时刻选择器 ***
        return _ManualTimePicker(initialDateTime: initialDateTime, onDateTimeChanged: onDateTimeChanged);
      case DatePickerMode.editDateTime:
        return Container();
    }
  }

  static Widget _buildBottomButtons(VoidCallback onCancel, VoidCallback onConfirm) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
      child: Row(
        children: [
          Expanded(
            child: ElevatedButton(
              onPressed: onCancel,
              style: ElevatedButton.styleFrom(
                foregroundColor: AppColors.of(NavigationService.context).whiteColor,
                backgroundColor: AppColors.of(NavigationService.context).backgroundColor,
                padding: const EdgeInsets.symmetric(vertical: 12.0),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24.0)),
              ),
              child: Text(
                '取消',
                style: TextStyle(color: AppColors.of(NavigationService.context).textColors3),
              ),
            ),
          ),
          const SizedBox(width: 16.0),
          Expanded(
            child: ElevatedButton(
              onPressed: onConfirm,
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: AppColors.of(NavigationService.context).primaryColor,
                padding: const EdgeInsets.symmetric(vertical: 12.0),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24.0)),
              ),
              child: Text(
                '确定',
                style: TextStyle(color: AppColors.of(NavigationService.context).whiteColor),
              ),
            ),
          ),
        ],
      ),
    );
  }

  static String formatDate(DateTime date) => '${date.year}年${date.month}月${date.day}日';
  static String formatTime(DateTime time) =>
      '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
  static String formatFilterDate(DateTime date, FilterType type) {
    switch (type) {
      case FilterType.week:
        final DateTime weekStart = date.subtract(Duration(days: date.weekday - 1));
        final DateTime weekEnd = weekStart.add(const Duration(days: 6));
        return '${weekStart.year}.${weekStart.month.toString().padLeft(2, '0')}.${weekStart.day.toString().padLeft(2, '0')}~${weekEnd.year}.${weekEnd.month.toString().padLeft(2, '0')}.${weekEnd.day.toString().padLeft(2, '0')}';
      case FilterType.month:
        return '${date.year}年${date.month}月';
      case FilterType.year:
        return '${date.year}年';
    }
  }
}

// 定义哪个部分是展开的
enum _AccordionSection { date, time }

/// 日期和时间选择组合组件 (手风琴效果版本)
class _DateTimePickerBody extends StatefulWidget {
  const _DateTimePickerBody({
    required this.initialDateTime,
    required this.onDateTimeChanged,
    required this.onCancel,
    required this.onConfirm,
    required this.title,
  });

  final DateTime initialDateTime;
  final ValueChanged<DateTime> onDateTimeChanged;
  final VoidCallback onCancel;
  final VoidCallback onConfirm;
  final String title;

  @override
  State<_DateTimePickerBody> createState() => _DateTimePickerBodyState();
}

class _DateTimePickerBodyState extends State<_DateTimePickerBody> {
  late DateTime _selectedDateTime;
  _AccordionSection _expandedSection = _AccordionSection.date;

  @override
  void initState() {
    super.initState();
    _selectedDateTime = widget.initialDateTime;
  }

  void _onDateChanged(DateTime dateTime) {
    // 日期变化时只更新年月日
    final newDateTime = DateTime(
      dateTime.year,
      dateTime.month,
      dateTime.day,
      _selectedDateTime.hour,
      _selectedDateTime.minute,
    );
    setState(() => _selectedDateTime = newDateTime);
    widget.onDateTimeChanged(newDateTime);
  }

  void _onTimeChanged(DateTime dateTime) {
    // 时间变化时只更新时分
    final newDateTime = DateTime(
      _selectedDateTime.year,
      _selectedDateTime.month,
      _selectedDateTime.day,
      dateTime.hour,
      dateTime.minute,
    );
    setState(() => _selectedDateTime = newDateTime);
    widget.onDateTimeChanged(newDateTime);
  }

  void _setExpandedSection(_AccordionSection section) {
    setState(() {
      _expandedSection = section;
    });
  }

  Widget _buildAccordionSection({
    required _AccordionSection section,
    required String title,
    required String value,
    required Widget picker,
  }) {
    final bool isExpanded = _expandedSection == section;

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        InkWell(
          onTap: () => _setExpandedSection(section),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  title,
                  style: TextStyle(fontSize: 17.0, fontWeight: isExpanded ? FontWeight.bold : FontWeight.normal),
                ),
                Text(value, style: const TextStyle(fontSize: 17.0, color: Colors.grey)),
              ],
            ),
          ),
        ),
        AnimatedSize(
          duration: const Duration(milliseconds: 300),
          curve: Curves.fastOutSlowIn,
          child: Container(
            child: isExpanded ? picker : null,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          alignment: Alignment.center,
          child: Text(widget.title, style: const TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
        ),
        _buildAccordionSection(
          section: _AccordionSection.date,
          title: '日期',
          value: CustomDatePicker.formatDate(_selectedDateTime),
          picker: _ManualDatePicker(
            initialDateTime: _selectedDateTime,
            onDateTimeChanged: _onDateChanged,
          ),
        ),
        const Divider(height: 1, indent: 16, endIndent: 16),
        _buildAccordionSection(
          section: _AccordionSection.time,
          title: '时刻',
          value: CustomDatePicker.formatTime(_selectedDateTime),
          picker: _ManualTimePicker(
            initialDateTime: _selectedDateTime,
            onDateTimeChanged: _onTimeChanged,
          ),
        ),
        CustomDatePicker._buildBottomButtons(widget.onCancel, widget.onConfirm),
      ],
    );
  }
}
